const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const db = require('../config/database');

// 中间件：验证JWT token
const verifyToken = (req, res, next) => {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    if (!token) {
        return res.status(401).json({ msg: '未提供访问令牌' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        res.status(401).json({ msg: '无效的访问令牌' });
    }
};

// 获取统计摘要数据
router.get('/summary', verifyToken, async (req, res) => {
    try {
        // 获取总借阅量
        const [totalBorrows] = await db.pool.query('SELECT COUNT(*) as total FROM borrows');
        
        // 获取本月借阅量
        const [monthlyBorrows] = await db.pool.query(
            'SELECT COUNT(*) as total FROM borrows WHERE MONTH(borrow_date) = MONTH(CURRENT_DATE()) AND YEAR(borrow_date) = YEAR(CURRENT_DATE())'
        );
        
        // 获取当前借出数量
        const [currentBorrows] = await db.pool.query(
            'SELECT COUNT(*) as total FROM borrows WHERE return_date IS NULL'
        );
        
        // 获取逾期数量
        const [overdueBorrows] = await db.pool.query(
            'SELECT COUNT(*) as total FROM borrows WHERE return_date IS NULL AND due_date < CURRENT_DATE()'
        );

        res.json({
            code: 0,
            msg: '成功',
            data: {
                total_borrows: totalBorrows[0].total,
                monthly_borrows: monthlyBorrows[0].total,
                current_borrows: currentBorrows[0].total,
                overdue_borrows: overdueBorrows[0].total
            }
        });
    } catch (error) {
        console.error('获取统计摘要失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 获取月度借阅趋势
router.get('/monthly-trend', verifyToken, async (req, res) => {
    const { months = 6 } = req.query;
    
    try {
        const [trend] = await db.pool.query(
            `SELECT 
                DATE_FORMAT(borrow_date, '%Y-%m') as month,
                COUNT(*) as count
            FROM borrows
            WHERE borrow_date >= DATE_SUB(CURRENT_DATE(), INTERVAL ? MONTH)
            GROUP BY DATE_FORMAT(borrow_date, '%Y-%m')
            ORDER BY month ASC`,
            [months]
        );

        res.json({ code: 0, msg: '成功', data: trend });
    } catch (error) {
        console.error('获取月度趋势失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 获取年龄分布
router.get('/age-distribution', verifyToken, async (req, res) => {
    try {
        const [distribution] = await db.pool.query(
            `SELECT 
                CASE 
                    WHEN age BETWEEN 18 AND 22 THEN '18-22岁'
                    WHEN age BETWEEN 23 AND 30 THEN '23-30岁'
                    WHEN age BETWEEN 31 AND 40 THEN '31-40岁'
                    ELSE '40岁以上'
                END as age_group,
                COUNT(*) as count
            FROM users
            GROUP BY age_group
            ORDER BY age_group`
        );

        res.json({ code: 0, msg: '成功', data: distribution });
    } catch (error) {
        console.error('获取年龄分布失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 获取专业分布
router.get('/major-distribution', verifyToken, async (req, res) => {
    try {
        const [distribution] = await db.pool.query(
            `SELECT 
                major,
                COUNT(DISTINCT id) as count
            FROM users
            GROUP BY major
            ORDER BY count DESC
            LIMIT 5`
        );

        res.json({ code: 0, msg: '成功', data: distribution });
    } catch (error) {
        console.error('获取专业分布失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 获取热门图书排行
router.get('/popular-books', verifyToken, async (req, res) => {
    try {
        const [popularBooks] = await db.pool.query(
            `SELECT 
                b.title,
                COUNT(*) as borrow_count
            FROM borrows br
            JOIN books b ON br.book_id = b.id
            GROUP BY b.id, b.title
            ORDER BY borrow_count DESC
            LIMIT 5`
        );

        res.json({ code: 0, msg: '成功', data: popularBooks });
    } catch (error) {
        console.error('获取热门图书失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 获取最新活动
router.get('/recent-activities', verifyToken, async (req, res) => {
    try {
        const [activities] = await db.pool.query(
            `SELECT 
                sl.action,
                sl.description,
                sl.created_at,
                u.username
            FROM system_logs sl
            LEFT JOIN users u ON sl.user_id = u.id
            ORDER BY sl.created_at DESC
            LIMIT 10`
        );

        // 格式化活动数据
        const formattedActivities = activities.map(activity => {
            let icon = 'fas fa-info-circle';
            let title = activity.description;

            // 根据action类型设置不同的图标
            switch(activity.action) {
                case 'book_add':
                case 'book_update':
                    icon = 'fas fa-book';
                    break;
                case 'user_create':
                    icon = 'fas fa-user';
                    break;
                case 'borrow_book':
                case 'return_book':
                    icon = 'fas fa-hand-holding';
                    break;
            }

            return {
                icon,
                title,
                time: new Date(activity.created_at).toLocaleString('zh-CN', {
                    hour12: false,
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                })
            };
        });

        res.json({ code: 0, msg: '成功', data: formattedActivities });
    } catch (error) {
        console.error('获取最新活动失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

module.exports = router;